﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Runtime.Serialization;

namespace Crm2011.Framework.Core
{
  // c:\Users\All Users\IsolatedStorage

  public static class IsolatedStorage
  {
    /// <summary>
    /// Saves generic object to disc.
    /// </summary>
    /// <typeparam name="T">type of the generic object</typeparam>
    /// <param name="fileName">Name of the file.</param>
    /// <param name="value">The Generic Object</param>
    public static void SaveToDisc<T>(string fileName, T value) 
    {
      try
      {
        Trace.Default.Debug("Saving Object '{0}' to file '{1}'", typeof(T).Name, fileName);
        using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetMachineStoreForDomain())
        {
          using (var s = new IsolatedStorageFileStream( fileName, FileMode.Create, isolatedStorageFile))
          {
            var ds = new DataContractSerializer(typeof(T)); 
            ds.WriteObject(s, value);
          }
        }
      }
      catch (Exception ex)
      {
        Trace.Default.LogException(ex);
      }
    }



    /// <summary>
    /// Reads a generic object from disc.
    /// </summary>
    /// <typeparam name="T">Type of the generic object</typeparam>
    /// <returns></returns>
    public static T ReadFromDisc<T>(string fileName) where T : class   
    {
      T result = null;
      try
      {
        using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetMachineStoreForDomain())
        {
          if (isolatedStorageFile.GetFileNames("*.*").Contains(fileName))
          {
            Trace.Default.Debug("Loading Object '{0}' from file '{1}'", typeof (T).Name, fileName);
            using (var isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isolatedStorageFile))
            {
              var ds = new DataContractSerializer(typeof (T));
              result = (T) ds.ReadObject(isfs);
            }
          }
        }
      }
      catch (Exception ex)
      {
        Trace.Default.LogException(ex);
      }
      return result;
    }

  }
}